package cn.pegasus.teamwork.util;

import java.text.DateFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 时间比价工具类
 * 
 * @author Administrator
 *
 */
public class DateCompareUtil {

	public static final String FND = "yyyyMMdd";
	private static final String timeP = "yyyy-MM-dd";

	public static boolean twoHours(Date date1, Date date2) {
		long beginTime = date1.getTime();
		long endTime = date2.getTime();
		long hours = (long) ((endTime - beginTime) / (1000 * 60 * 60));
		if (hours > 2) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 判断时间是否在时间段内
	 * 
	 * @param nowTime
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
		Calendar date = Calendar.getInstance();
		date.setTime(nowTime);

		Calendar begin = Calendar.getInstance();
		begin.setTime(beginTime);

		Calendar end = Calendar.getInstance();
		end.setTime(endTime);

		if (date.after(begin) && date.before(end)) {
			return true;
		} else {
			return false;
		}
	}

	public static Date getNowDate() {
		try {
			Date date = new Date();
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			Date dateTrans;
			dateTrans = format.parse(format.format(date));
			return dateTrans;
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return null;
	}

	public static Date getNowDate(String times) {
		try {
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			Date dateTrans;
			dateTrans = format.parse(times);
			return dateTrans;
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return null;
	}

	public static Date getDateToString(String times) {
		try {
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Date dateTrans;
			dateTrans = format.parse(times);
			return dateTrans;
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return null;
	}

	public static String getDateToString(Date date) {
		try {
			// 格式 24小时制：2016-07-06 09:39:58
			DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // HH表示24小时制；
			String formatDate = dFormat.format(date);
			return formatDate;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public static String getDateToDateString(Date date) {
		try {
			// 格式 24小时制：2016-07-06 09:39:58
			DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd"); // HH表示24小时制；
			String formatDate = dFormat.format(date);
			return formatDate;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	
	public static String getDateToMils(Date date) {
		try {
			// 格式 24小时制：2016-07-06 09:39:58
			DateFormat dFormat = new SimpleDateFormat("HH:mm"); // HH表示24小时制；
			String formatDate = dFormat.format(date);
			return formatDate;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public static String getDateString(String str) {
		try {
			Date date = new Date();
			DateFormat format = new SimpleDateFormat(str);

			String dateTrans = format.format(date);
			return dateTrans;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Map<String, Object> getMonthFirstLast() {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		// 获取当前月第一天：
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, 0);
		c.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
		String first = format.format(c.getTime());
		resultMap.put("createTimeBegin", first);

		// 获取当前月最后一天
		Calendar ca = Calendar.getInstance();
		ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
		String last = format.format(ca.getTime());
		resultMap.put("createTimeEnd", last);

		return resultMap;
	}

	public static List<String> getDayForHoursForList(Date date, int count) {
		List<String> lis = new ArrayList<String>();
		// 系统切割的时间上午
		Map<Integer, String> newmap = getDayForHours(date, count);
		if (newmap != null && newmap.size() > 0) {
			for (Map.Entry<Integer, String> entry : newmap.entrySet()) {
				lis.add(entry.getValue());
			}
		}
		// 系统切割的时间下午
		Map<Integer, String> anewmap = getDayForHoursByAfternoon(date, count);
		for (Map.Entry<Integer, String> entry : anewmap.entrySet()) {
			lis.add(entry.getValue());
		}
		return lis;
	}

	/**
	 * 通过传入日期，获取每隔多久时间段
	 * 
	 * @param date
	 * @param count
	 * @return
	 */
	public static Map<Integer, String> getDayForHours(Date date, int count) {
		Map<Integer, String> resultMap = new HashMap<Integer, String>();
		List<Date> ds = getResult(date, count);
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		for (int i = 0; i < ds.size(); i++) {
			if (i + 1 < ds.size() && ds.get(i) != null && ds.get(i + 1) != null) {
				if (ds.get(i).getTime() <= ds.get(i + 1).getTime() - count * 60000) {
					resultMap.put(i + 1, sdf.format(ds.get(i)) + "-" + sdf.format(ds.get(i + 1)));
				}
			}
		}

		return resultMap;
	}

	/**
	 * 通过传入日期，获取每隔多久时间段
	 * 
	 * @param date
	 * @param count
	 * @return
	 */
	public static Map<Integer, String> getDayForHoursByAfternoon(Date date, int count) {
		Map<Integer, String> resultMap = new HashMap<Integer, String>();
		List<Date> ds = getResultByAfternoon(date, count);
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		for (int i = 0; i < ds.size(); i++) {
			if (i + 1 < ds.size() && ds.get(i) != null && ds.get(i + 1) != null) {
				if (ds.get(i).getTime() <= ds.get(i + 1).getTime() - count * 60000) {
					resultMap.put(i + 1, sdf.format(ds.get(i)) + "-" + sdf.format(ds.get(i + 1)));
				}
			}
		}

		return resultMap;
	}

	/**
	 * 通过传入日期，获取每隔多久时间段
	 * 
	 * @param date
	 * @param count
	 * @return
	 */
	public static String getDayForHours(Date bdate, Date edate) {
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		String rs = sdf.format(bdate) + "-" + sdf.format(edate);
		return rs;
	}

	/**
	 * 获取时间段内的日期切割数字
	 * 
	 * @param date
	 * @param count
	 * @return
	 */
	public static List<Date> getResult(Date date, int count) {
		Date start = dayStartDate(date);// 转换为天的起始date
		Date nextDayDate = nextDay(start);// 下一天的date
		Date nowDate = new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(nowDate);
		nowDate = c.getTime();
		List<Date> result = new ArrayList<Date>();
		if (nextDayDate.getTime() < new Date().getTime()) {
			while (start.compareTo(nextDayDate) <= 0) {
				result.add(start);
				// 日期加 count 分钟
				start = addFiveMin(start, count);
			}
		} else {
			if (nowDate.getTime() > start.getTime()) {
				while (nowDate.compareTo(nextDayDate) <= 0) {
					result.add(nowDate);
					// 日期加 count 分钟
					nowDate = addFiveMin(nowDate, count);
				}
			} else {
				while (start.compareTo(nextDayDate) <= 0) {
					result.add(start);
					// 日期加 count 分钟
					start = addFiveMin(start, count);
				}
			}
		}

		return result;
	}

	/**
	 * 通过传入日期，获取每隔多久时间段
	 * 
	 * @param date
	 * @param count
	 * @return
	 */
	public static Map<Integer, String> getDayForHoursByCustom(Date date, Date date2, int count) {
		Map<Integer, String> resultMap = new HashMap<Integer, String>();
		List<Date> ds = getResultForCustom(date, date2, count);
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		for (int i = 0; i < ds.size(); i++) {
			if (i + 1 < ds.size() && ds.get(i) != null && ds.get(i + 1) != null) {
				if (ds.get(i).getTime() <= ds.get(i + 1).getTime() - count * 60000) {
					resultMap.put(i + 1, sdf.format(ds.get(i)) + "-" + sdf.format(ds.get(i + 1)));
				}
			}
		}

		return resultMap;
	}

	/**
	 * 获取时间段内的日期切割数字
	 * 
	 * @param date
	 * @param count
	 * @return
	 */
	public static List<Date> getResultForCustom(Date start, Date nextDayDate, int count) {
		Calendar s = Calendar.getInstance();
		s.setTime(start);
		start = s.getTime();

		Calendar e = Calendar.getInstance();
		e.setTime(nextDayDate);
		nextDayDate = e.getTime();

		Date nowDate = new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(nowDate);
		nowDate = c.getTime();
		List<Date> result = new ArrayList<Date>();
		while (start.compareTo(nextDayDate) <= 0) {
			result.add(start);
			// 日期加 count 分钟
			start = addFiveMin(start, count);
		}
		return result;
	}

	/**
	 * 获取时间段内的日期切割数字
	 * 
	 * @param date
	 * @param count
	 * @return
	 */
	public static List<Date> getResultByAfternoon(Date date, int count) {
		Date start = dayStartDateByAfternoon(date);// 转换为天的起始date
		Date nextDayDate = nextDaybyAfternoon(start);// 下一天的date

		List<Date> result = new ArrayList<Date>();
		Date nowDate = new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(nowDate);
		nowDate = c.getTime();
		// 判断传入时间，前面已经判断了是今天

		if (nextDayDate.getTime() < nowDate.getTime()) {
			while (start.compareTo(nextDayDate) <= 0) {
				result.add(start);
				// 日期加 count 分钟
				start = addFiveMin(start, count);
			}
		} else {
			if (nowDate.getTime() > start.getTime()) {
				while (start.compareTo(nowDate) <= 0) {
					result.add(start);
					// 日期加 count 分钟
					start = addFiveMin(start, count);
				}
				while (nowDate.compareTo(nextDayDate) <= 0) {
					result.add(nowDate);
					// 日期加 count 分钟
					nowDate = addFiveMin(nowDate, count);
				}
			} else {
				while (start.compareTo(nextDayDate) <= 0) {
					result.add(start);
					// 日期加 count 分钟
					start = addFiveMin(start, count);
				}
			}
		}

		return result;
	}

	private static Date addFiveMin(Date start, int offset) {
		Calendar c = Calendar.getInstance();
		c.setTime(start);
		c.add(Calendar.MINUTE, offset);
		return c.getTime();
	}

	/**
	 * 获得指定日期的后一天
	 * 
	 * @param specifiedDay
	 * @return
	 */
	public static Date nextDay(Date start) {
		Calendar c = Calendar.getInstance();
		Date date = start;
		c.setTime(date);
		// c.set(Calendar.DATE, 13);
		c.set(Calendar.HOUR_OF_DAY, 13);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		return c.getTime();
	}

	/**
	 * 获得指定日期的后一天
	 * 
	 * @param specifiedDay
	 * @return
	 */
	public static Date nextDaybyAfternoon(Date start) {
		Calendar c = Calendar.getInstance();
		Date date = start;
		c.setTime(date);
		// c.set(Calendar.DATE, 21);
		c.set(Calendar.HOUR_OF_DAY, 21);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		return c.getTime();
	}

	/**
	 * 获取上个月的开始日期和结束日期
	 */

	public static List<String> getDatStartAndEndDay() throws Exception {
		List<String> lst = new ArrayList<String>();
		Date today = new Date();
		Date dateTime = lastMonthDate(today);
		Date date = getMonthStart(dateTime);
		Date monthEnd = getMonthEnd(dateTime);
		lst.add(getStrDate(date, timeP));
		lst.add(getStrDate(monthEnd, timeP));
		return lst;
	}

	/**
	 * date转string
	 * 
	 * @return
	 */
	public static String getStrDate(Date date, String timeP) {
		Format f = new SimpleDateFormat(timeP);
		String dateStr = f.format(date);
		return dateStr;
	}

	/**
	 * 一个月的开始时间
	 * 
	 * @param date
	 * @return
	 */
	public static Date getMonthStart(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int index = calendar.get(Calendar.DAY_OF_MONTH);
		calendar.add(Calendar.DATE, (1 - index));
		return calendar.getTime();
	}

	/**
	 * 获取一个月的结束时间
	 * 
	 * @return
	 */
	public static Date getMonthEnd(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.MONTH, 1);
		int index = calendar.get(Calendar.DAY_OF_MONTH);
		calendar.add(Calendar.DATE, (-index));
		return calendar.getTime();
	}

	/**
	 * 获取上个月的日期
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("static-access")
	public static Date lastMonthDate(Date date) throws Exception {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(date);
		calendar.add(calendar.MONTH, -1);
		return calendar.getTime();
	}

	/**
	 * 获取当天日期的开始时期
	 * 
	 * @param date
	 * @return
	 */
	public static Date dayStartDate(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.HOUR_OF_DAY, 9);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		return c.getTime();

	}

	/**
	 * 获取当天日期的开始时期
	 * 
	 * @param date
	 * @return
	 */
	public static Date dayStartDateByAfternoon(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.HOUR_OF_DAY, 14);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		return c.getTime();

	}

	/**
	 * 判断某一时间是否在一个区间内
	 * 
	 * @param sourceTime
	 *            时间区间,半闭合,如[10:00-20:00)
	 * @param curTime
	 *            需要判断的时间 如10:00
	 * @return
	 * @throws IllegalArgumentException
	 */
	public static boolean isInTime(String sourceTime, String curTime) {
		if (sourceTime == null || !sourceTime.contains("-") || !sourceTime.contains(":")) {
			throw new IllegalArgumentException("Illegal Argument arg:" + sourceTime);
		}
		if (curTime == null || !curTime.contains(":")) {
			throw new IllegalArgumentException("Illegal Argument arg:" + curTime);
		}
		String[] args = sourceTime.split("-");
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		try {
			long now = sdf.parse(curTime).getTime();
			long start = sdf.parse(args[0]).getTime();
			long end = sdf.parse(args[1]).getTime();
			if (args[1].equals("00:00")) {
				args[1] = "24:00";
			}
			if (end < start) {
				if (now >= end && now < start) {
					return false;
				} else {
					return true;
				}
			} else {
				if (now >= start && now < end) {
					return true;
				} else {
					return false;
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
			throw new IllegalArgumentException("Illegal Argument arg:" + sourceTime);
		}

	}

	/**
	 * 判断某一时间是否在一个区间内
	 * 
	 * @param sourceTime
	 *            时间区间,半闭合,如[10:00-20:00)
	 * @param curTime
	 *            需要判断的时间 如10:00
	 * @return
	 * @throws IllegalArgumentException
	 */
	public static boolean isInTimeOn(String sourceTime, String curTime) {
		if (sourceTime == null || !sourceTime.contains("-") || !sourceTime.contains(":")) {
			throw new IllegalArgumentException("Illegal Argument arg:" + sourceTime);
		}
		if (curTime == null || !curTime.contains(":")) {
			throw new IllegalArgumentException("Illegal Argument arg:" + curTime);
		}
		String[] args = sourceTime.split("-");
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		try {
			long now = sdf.parse(curTime).getTime();
			long start = sdf.parse(args[0]).getTime();
			long end = sdf.parse(args[1]).getTime();
			if (args[1].equals("00:00")) {
				args[1] = "24:00";
			}
			if (now > end) {
				return false;
			} else {
				return true;
			}
		} catch (ParseException e) {
			e.printStackTrace();
			throw new IllegalArgumentException("Illegal Argument arg:" + sourceTime);
		}

	}

	/**
	 * 判断时间是不是今天
	 * 
	 * @param date
	 * @return 是返回true，不是返回false
	 */
	public static int isNowObsolete(Date startDate, Date endDate) {
		Calendar start = Calendar.getInstance();
		Calendar end = Calendar.getInstance();
		start.setTime(startDate);
		end.setTime(endDate);
		// 开始时间小于结束时间
		if (start.before(end)) {
			return 1;
			// 开始时间大于结束时间
		} else if (start.after(end)) {
			return 2;
			// 开始时间等于结束时间
		} else if (start.equals(end)) {
			return 0;
		}
		return -1;
	}

	/**
	 * 判断时间是不是今天
	 * 
	 * @param date
	 * @return 是返回true，不是返回false
	 */
	public static boolean isToday(Date date) {
		// 当前时间
		Date now = new Date();

		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		// 获取今天的日期
		String nowDay = sf.format(now);

		// 对比的时间
		String day = sf.format(date);

		System.out.println(day.equals(nowDay));
		return day.equals(nowDay);

	}

	/**
	 * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
	 * 
	 * @param strDate
	 * @return
	 */
	public static Date strToDateLong(String strDate) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ParsePosition pos = new ParsePosition(0);
		Date strtodate = formatter.parse(strDate, pos);
		return strtodate;
	}

	public static Date stringToDate(String str) {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			// Fri Feb 24 00:00:00 CST 2012
			date = format.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		// 2012-02-24
		// date = java.sql.Date.valueOf(str);
		//
		return date;
	}

	public static Date paraseStringToDate(String timestr) throws Exception {
		Format f = new SimpleDateFormat("yyyy-MM-dd");
		Date date = (Date) f.parseObject(timestr);
		return date;
	}
	public static Date getNextDate(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, +1); // 今天的时间加一天
		date = calendar.getTime();
		return date;
	}
	public static void main(String[] args) {
		System.out.println(isInTime( "9:00-13:00","09:50-10:15"));
	}
}
